package org.byqh.dqeai.controller;

import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.byqh.dqeai.common.Json;
import org.byqh.dqeai.dto.EaiSysOrganizationDTO;
import org.byqh.dqeai.dto.common.PageData;
import org.byqh.dqeai.entity.EaiSysOrganization;
import org.byqh.dqeai.entity.proxy.EaiSysOrganizationProxy;
import org.byqh.dqeai.util.SpringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/sysorg")
@Tag(name = "系统[EaiSysOrganization] - 组织管理")
public class EaiSysOrganizationController extends BaseController<EaiSysOrganization, EaiSysOrganizationProxy> {
    public String GetPath(String orgId) {
        String sql = String.format("""
                SELECT SYS_CONNECT_BY_PATH (org_name, '/') AS path
                        FROM (    SELECT org_id,
                                         parent_id,
                                         org_name,
                                         CONNECT_BY_ISLEAF AS cbleaf
                                  FROM EAI_SYS_ORGANIZATION
                                           START WITH org_id = '%s'
                                  CONNECT BY PRIOR parent_id = org_id)
                        WHERE CONNECT_BY_ISLEAF = 1
                            START WITH cbleaf = 1
                        CONNECT BY PRIOR org_id = parent_id
                """, orgId);

        var value = easyQueryClient.sqlQuery(sql, String.class)
                .stream()
                .findFirst()
                .orElse(null);

        return value == null ? "" : value.toString();
    }

    @Override
    @GetMapping(value = "/get/{id}")
    public Json<EaiSysOrganization> get(String id) {
        return super.get(id);
    }

    @Override
    @PutMapping(value = "/put")
    public Json<Boolean> put(EaiSysOrganization dto) {
        return super.put(dto);
    }

    @Override
    @PostMapping(value = "/post")
    public Json<Boolean> post(EaiSysOrganization dto) {
        return super.post(dto);
    }

    @GetMapping(value = "/{orgId}")
    public Json<EaiSysOrganizationDTO> get2(@PathVariable String orgId) {
        var obj = getEntityQueryable()
                .whereById(orgId)
                .selectAutoInclude(EaiSysOrganizationDTO.class)
                .firstOrNull();

        return Json.success(obj);
    }

    @PostMapping(value = "/")
    public Json<Boolean> post2(@RequestBody EaiSysOrganizationDTO dto) {
        var now = LocalDateTime.now();
        dto.setCreateDate(now);
        dto.setUpdateDate(now);

        return easyEntityQuery.insertable(dto).executeRows() > 0 ? Json.success() : Json.error();
    }

    @PutMapping(value = "/")
    public Json<Boolean> put2(@RequestBody EaiSysOrganizationDTO dto) {
        var one = this.getEntityQueryable()
                .where(s -> s.orgId().eq(dto.getOrgId()))
                .firstOrNull();

        if (one == null) {
            return Json.error("不存在要更改的数据", false, HttpStatus.OK.value());
        }

        BeanUtils.copyProperties(dto, one, SpringUtils.getNullPropertyNames(dto));
        one.setUpdateDate(LocalDateTime.now());

        return this.update(one);
    }

    /**
     * 删除组织机构接口对象信息
     */
    @DeleteMapping(value = "/{id}")
    @Override
    public Json<Boolean> delete(@PathVariable String id) {
        if (StringUtils.isBlank(id)) {
            return Json.error();
        }

        String sql = """
                DELETE from EAI_SYS_ORGANIZATION
                         WHERE ORG_ID IN
                               (select ORG_ID
                                  FROM EAI_SYS_ORGANIZATION
                                 start with ORG_ID ='%s'
                                connect by prior ORG_ID = PARENT_ID)
                """;

        sql = String.format(sql, id);

        easyQueryClient.sqlExecute(sql);

        return Json.success();
    }

    /**
     * 查询组织机构接口对象信息分页列表
     */
    @PostMapping(value = "/page")
    public Json<PageData<EaiSysOrganizationDTO>> page(@RequestBody(required = false) EaiSysOrganizationDTO dto) {
        var tmp = this.listPageImpl(EaiSysOrganizationDTO.class, dto.getPage().getPage(), dto.getPage().getSize(), query -> {
            return query.orderBy(e -> e.orgLevel().asc())
                    .orderBy(e -> e.orgId().asc());
        }).getData();

        return Json.success(new PageData<>(tmp));
    }

    /**
     * 查询全部组织机构接口对象信息列表
     */
    @GetMapping(value = "/list")
    public Json<List<EaiSysOrganizationDTO>> list(
            @RequestParam(defaultValue = "") String parentId) {

        return this.listImpl(EaiSysOrganizationDTO.class, query -> {
            if (!StringUtils.isBlank(parentId)) {
                String sql = String.format("""
                        select ORG_ID
                             FROM EAI_SYS_ORGANIZATION
                             start with ORG_ID = '%s'
                             connect by prior ORG_ID = PARENT_ID
                        """, parentId);

                query = query.where(o -> o.orgId().in(easyQueryClient.queryable(sql, String.class).toList()));
            }

            return query;
        });
    }
}